Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).

For example:

Given binary tree [3,9,20,null,null,15,7],

  1. 3
  2. / \
  3. 9 20
  4. / \
  5. 15 7

return its zigzag level order traversal as:

  1. [
  2. [3],
  3. [20,9],
  4. [15,7]
  5. ]

Solution:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
  12. List<List<Integer>> res = new ArrayList<>();
  13. if (root == null) {
  14. return res;
  15. }
  16. List<Integer> list = new ArrayList<>();
  17. Stack<TreeNode> s1 = new Stack<>();
  18. Stack<TreeNode> s2 = new Stack<>();
  19. boolean leftToRight = true;
  20. s1.push(root);
  21. while (!s1.isEmpty()) {
  22. TreeNode node = s1.pop();
  23. list.add(node.val);
  24. if (leftToRight) {
  25. if (node.left != null) {
  26. s2.push(node.left);
  27. }
  28. if (node.right != null) {
  29. s2.push(node.right);
  30. }
  31. } else {
  32. if (node.right != null) {
  33. s2.push(node.right);
  34. }
  35. if (node.left != null) {
  36. s2.push(node.left);
  37. }
  38. }
  39. if (s1.isEmpty()) {
  40. leftToRight = !leftToRight;
  41. res.add(new ArrayList<>(list));
  42. list = new ArrayList<>();
  43. s1 = s2;
  44. s2 = new Stack<>();
  45. }
  46. }
  47. return res;
  48. }
  49. }